import { Lazyload } from 'vant';
import error from '@/assets/images/default/no-photo4-3.png';
import head from '@/assets/images/default/head.png';
import { nextTick } from 'vue';
const Directive = (Vue: any) => {
	// 注册时可以配置额外的选项
	Vue.use(Lazyload, {
		lazyComponent: true,
		error
	});

	// 默认头像
	Vue.directive('headImg', {
		// eslint-disable-next-line @typescript-eslint/no-shadow
		mounted(el: any, binding: any) {
			nextTick(() => {
				console.log(binding);
				console.log(binding.value);
			});
			// 创建一个IntersectionObserver实例
			const observer = new IntersectionObserver(
				([entry]) => {
					if (entry.isIntersecting) {
						// 如果图片进入可视区域
						const imgSrc = binding.value;
						// 设置图片源地址
						el.src = imgSrc;

						// 观察器不再需要观察此元素
						observer.unobserve(el);
						// 如果图片报错则展示默认图
						el.onerror = () => {
							el.src = head;
						};
					}
				},
				// 可配置阈值，表示元素多少比例进入视窗才触发回调
				{ threshold: 0.5 }
			);
			// 将元素添加到观察器的目标列表中
			observer.observe(el);

			// 在指令解绑时清理
			// eslint-disable-next-line camelcase
			el.lazy_observer = observer;
		},
		// 更新时触发
		updated(el: any, binding: any) {
			if (el.src.includes(head) && binding.value) {
				el.src = binding.value;
				el.onerror = () => {
					el.src = head;
				};
			}
		},
		// eslint-disable-next-line @typescript-eslint/no-shadow
		unmounted(el: any) {
			// 解除IntersectionObserver对元素的监听
			const observer = el.lazy_observer;
			if (observer) {
				observer.unobserve(el);
			}
		}
	});
};
export default Directive;
